import React, { Component } from 'react';
import './Shoprenz.css'
import { Input, DatePicker, Checkbox, Upload, Modal, Button, message } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios'
import moment from 'moment'
const { confirm } = Modal;
class Shoprenz extends Component {
  constructor(props) {
    super(props)
    this.state = {
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList: [],
      uname: 'shop01',
      qiyename: '',
      youxiaotime: '',
      imageUrl: '',
      checked: false
    };
  }
  componentDidMount() {
    if (sessionStorage.getItem("userlist")) {
      this.setState({
        uname: JSON.parse(sessionStorage.getItem("userlist"))[0]
      })
    }
    this.getDate();
  }
  getDate() {
    axios.post("/api//backstage/shop/findShopInformation?userName=" + this.state.uname
    ).then((res) => {
      if (res.data.code === 200) {
        this.setState({
          qiyename: res.data.data.shopName,
          youxiaotime: res.data.data.shopLicenseTime,
          imageUrl: "http://172.17.6.224:8085" + res.data.data.shopLicense
        })

        if (this.state.youxiaotime === '长期' || this.state.youxiaotime === "无") {
          this.setState({
            checked: true
          })
        }
      }
    })
  }
  //弹出确定对话框
  showConfirm() {
    let that = this
    confirm({
      title: '将完成店铺设置, 是否继续?',
      icon: <ExclamationCircleOutlined />,
      cancelText: '返回',
      okText: '确定',
      onOk() {
        let imgFile = that.state.fileList[0] ? that.state.fileList[0].originFileObj : undefined; //获取到上传的图片
        let formData = new FormData(); //通过formdata上传
        var time = new Date(that.state.youxiaotime);
        let y = time.getFullYear(); //时间转换
        let m = time.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        let d = time.getDate();
        d = d < 10 ? "0" + d : d;
        let h = time.getHours();
        h = h < 10 ? "0" + h : h;
        let minute = time.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        let second = time.getSeconds();
        second = second < 10 ? "0" + second : second;
        let times =
          y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
        formData.append("file", imgFile);
        formData.append("userName", that.state.uname);
        formData.append("shopName", that.state.qiyename);
        formData.append("shopLicenseTime", times);
        if (imgFile === undefined) {
          message.warning(' 营业执照必须上传', 2.5)
        } else {
          axios({
            method: "post",
            url: "/api/backstage/shop/uploadShopLicense",
            header: { "Content-Type": "multipart/form-data" },
            data: formData,
          }).then((res) => {
            if (res.data.code !== 200) {
              message.error(' 店铺认证失败', 2.5)
            } else {
              that.getDate();
              message.success(' 店铺认证成功', 2.5)
            }
          }).catch(err => {
            message.error(' 数据库错误', 2.5)
          })
        }
      },
      onCancel() {

      },
    });
  }
  //输入框
  inputChange(e) {
    this.setState({
      qiyename: e.target.value
    })
  }
  //日期选择
  onChange = (date, dateString) => {
    this.setState({
      youxiaotime: dateString
    })
  }
  //复选框
  onCChange(e) {
    this.setState({
      checked: e.target.checked
    })
  }
  //图片
  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  handleCancel = () => this.setState({
    previewVisible: false
  });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };
  handleChange = ({ fileList }) => this.setState({
    fileList
  }, () => {
    console.log(this.state.fileList);
  });

  render() {

    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );


    return (
      <div className='content'>
        <div className='box'>
          <div className='hezi'>
            <div className='col'>
              <div className='title'>
                企业名称:
                    </div>
              <div className='nr'>
                <Input
                  placeholder="请输入"
                  value={this.state.qiyename}
                  onInput={this.inputChange.bind(this)} />
              </div>
            </div>
            <div className='col'>
              <div className='title'>
                工商营业执照有效截止时间:
                    </div>
              <div className='nr'>
                <DatePicker
                  onChange={this.onChange}
                  value={this.state.youxiaotime ? moment(this.state.youxiaotime) : undefined}
                />
                <Checkbox
                  onChange={this.onCChange.bind(this)}
                  checked={this.state.checked}>长期有效</Checkbox>
              </div>
            </div>
            <p>截止日期需大于60天，如截止日期为长期或无，请勾选“长期有效”</p>
            <div className='coltu'>
              <div className='title'>
                上传营业执照：
                    </div>
              <div className='nr'>

                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}

                >
                  {fileList.length >= 8 ? null : uploadButton}
                </Upload>
                <Modal
                  visible={previewVisible}
                  title={previewTitle}
                  footer={null}
                  onCancel={this.handleCancel}
                >
                  <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
              </div>
            </div>
            <div className='cols'>
              <p>1.请上传清晰、完整、无遮章物的营业执照照片.要求原件红章清晰</p>
              <p>2.如位复印件需加盖公司公章</p>
              <p>3支持扩展名,jpg .png，大小不超过5M</p>
            </div>
            <div>
              <Button type="primary" onClick={this.showConfirm.bind(this)}>提交</Button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Shoprenz;